<!--
  字段选择器组件
  用于在表单中选择字段

  属性:
  - modelValue: 选中的字段ID (v-model)
  - datasetId: 可选的数据集ID过滤器，若提供则只显示该数据集下的字段
  - placeholder: 占位符文本
  - disabled: 是否禁用
  - clearable: 是否可清空
  - multiple: 是否多选
-->
<template>
  <el-select
    v-model="selectedField"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    :multiple="multiple"
    :collapse-tags="multiple"
    :collapse-tags-tooltip="multiple"
    class="field-select"
    :loading="loading"
  >
    <el-option
      v-for="option in filteredFieldOptions"
      :key="option.value"
      :label="option.label"
      :value="option.value"
    >
      <div class="field-option">
        <span>{{ option.label }}</span>
        <el-tag size="small" :type="getFieldTypeTagType(getFieldType(option.value))">
          {{ getFieldTypeLabel(getFieldType(option.value)) }}
        </el-tag>
      </div>
    </el-option>
    <template #empty>
      <el-empty description="暂无字段" :image-size="60" />
    </template>
  </el-select>
</template>

<script setup>
import { computed, ref, watch, onMounted } from 'vue'
import { useDataFieldStore, fieldTypeOptions } from '../../stores/dataField'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: [Number, String, Array],
    default: null
  },
  datasetId: {
    type: [Number, String],
    default: null
  },
  placeholder: {
    type: String,
    default: '请选择字段'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: true
  },
  multiple: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change'])

// 获取字段 store
const dataFieldStore = useDataFieldStore()
const loading = ref(false)

// 预加载字段
onMounted(async () => {
  loading.value = true
  await dataFieldStore.fetchFields()
  loading.value = false
})

// 计算属性：字段选项
const fieldOptions = computed(() => dataFieldStore.fieldOptions)

// 根据数据集ID筛选字段选项
const filteredFieldOptions = computed(() => {
  if (!props.datasetId) {
    return fieldOptions.value
  }
  return fieldOptions.value.filter(option =>
    String(option.datasetId) === String(props.datasetId)
  )
})

// 计算属性：当前选中值
const selectedField = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
    emit('change', val)
  }
})

// 获取字段类型
const getFieldType = (fieldId) => {
  const field = dataFieldStore.getFieldById(fieldId)
  return field ? field.type : null
}

// 获取字段类型标签
const getFieldTypeLabel = (type) => {
  const option = fieldTypeOptions.find(opt => opt.value === type)
  return option ? option.label : '未知'
}

// 获取字段类型标签样式
const getFieldTypeTagType = (type) => {
  const typeMap = {
    int: 'success',
    float: 'success',
    string: 'info',
    datetime: 'warning',
    boolean: 'danger',
    json: 'info'
  }
  return typeMap[type] || ''
}

// 当数据集ID变化时，可能需要重置选中的字段
watch(() => props.datasetId, (newDatasetId) => {
  if (newDatasetId) {
    if (props.multiple && Array.isArray(selectedField.value)) {
      // 移除不属于当前数据集的字段
      selectedField.value = selectedField.value.filter(id => {
        const field = dataFieldStore.getFieldById(id)
        return field && String(field.datasetId) === String(newDatasetId)
      })
    } else if (selectedField.value) {
      // 单选模式
      const field = dataFieldStore.getFieldById(selectedField.value)
      if (field && String(field.datasetId) !== String(newDatasetId)) {
        selectedField.value = null
      }
    }
  }
}, { immediate: true })
</script>

<style scoped>
.field-select {
  width: 100%;
}

.field-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px;
}
</style>
